<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? '新增规格' : '编辑规格'" :close-on-click-modal="false"
             :close-on-press-escape="false">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="productId" label="商品">
        <ComSelectPage ref="newPageSelect" @selectPageChange="e=>dataForm.productId=e"
                       :getUrl="{
                          url:'/api/product/page',
                          method:'get',
                          params:{page: 1,limit: 10,total: 0},
                        }" :defaultValue="dataForm.productId"
                       clearable
                       selectLabel="productName"
                       selectValue="id"
                       selectLabelTwo="groupName"></ComSelectPage>
      </el-form-item>
      <el-form-item prop="price" label="商品价格">
        <el-input-number v-model="dataForm.price" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="marketPrice" label="划线价">
        <el-input-number v-model="dataForm.marketPrice" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="proProfit" label="省代收益">
        <el-input-number v-model="dataForm.proProfit" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="cityProfit" label="市代收益">
        <el-input-number v-model="dataForm.cityProfit" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="areaProfit" label="区县收益">
        <el-input-number v-model="dataForm.areaProfit" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="firstProfit" label="直推收益">
        <el-input-number v-model="dataForm.firstProfit" :precision="2" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="secProfit" label="间推收益">
        <el-input-number v-model="dataForm.secProfit" :precision="2" :min="0"></el-input-number>
      </el-form-item>
<!--      <el-form-item prop="points" label="赠予积分">-->
<!--        <el-input-number v-model="dataForm.points" :precision="2" :min="0"></el-input-number>-->
<!--      </el-form-item>-->
<!--      <el-form-item prop="specsName" label="商品规格">-->
<!--        <el-input v-model="dataForm.specsName" placeholder="规格的名称，如颜色、尺寸等"></el-input>-->
<!--      </el-form-item>-->
      <el-form-item prop="specsOption" label="规格名称">
        <el-input v-model="dataForm.specsOption" placeholder="规格的可选项，如红色、蓝色、XL、XXL等"></el-input>
      </el-form-item>
      <el-form-item prop="stock" label="库存数量">
        <el-input-number v-model="dataForm.stock" :precision="0" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item prop="imgUrl" label="主图">
        <div class="flex_center flex_wrap">
          <div class="img_con" v-if="dataForm.imgUrl">
            <el-image class="deduct_img" :src="dataForm.imgUrl" :preview-src-list="[dataForm.imgUrl]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(dataForm.imgUrl,1)"/>
          </div>
          <com-upload v-show="!dataForm.imgUrl" @get-url="getUrlOne"></com-upload>
        </div>
        <div style="color:#909399;"><el-icon class="el-icon-info"></el-icon>普通商品建议上传500x500；定制商品建议750x375</div>
      </el-form-item>
      <el-form-item prop="bodyImg" label="外盒">
        <div class="flex_center flex_wrap">
          <div class="img_con" v-if="dataForm.bodyImg">
            <el-image class="deduct_img" :src="dataForm.bodyImg" :preview-src-list="[dataForm.bodyImg]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(dataForm.bodyImg,2)"/>
          </div>
          <com-upload v-show="!dataForm.bodyImg" @get-url="getUrlTwo"></com-upload>
        </div>
        <div style="color:#909399;"><el-icon class="el-icon-info"></el-icon>建议上传750x375的图片</div>
      </el-form-item>
      <el-form-item prop="packageImg" label="瓶身">
        <div class="flex_center flex_wrap">
          <div class="img_con" v-if="dataForm.packageImg">
            <el-image class="deduct_img" :src="dataForm.packageImg" :preview-src-list="[dataForm.packageImg]"/>
            <i class="el-icon-error remove_img" @click="cancelImg(dataForm.packageImg,3)"/>
          </div>
          <com-upload v-show="!dataForm.packageImg" @get-url="getUrlThree"></com-upload>
        </div>
        <div style="color:#909399;"><el-icon class="el-icon-info"></el-icon>建议上传750x375的图片</div>
      </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'

export default {
  data() {
    return {
      visible: false,
      productList: [],//商品列表
      dataForm: {
        id: '',
        imgUrl: '',                         //针对该规格的图片链接（主图）
        bodyImg: '',                        //针对该规格的图片链接（外盒）
        packageImg: '',                     //针对该规格的图片链接（瓶身）
        price: 0,                           //针对该规格选项的价格
        marketPrice: '',	                  //针对该规格选项的划线价格
        productId: '',                      //关联到所属商品的ID
        specsName: '',	                    //规格的名称，如颜色、尺寸等
        specsOption: '',                    //规格的可选项，如红色、蓝色、XL、XXL等
        stock: '',                          //针对该规格选项的库存
        points: '',                         //购买产品可获得的积分
        proProfit:'',                       //省代收益
        cityProfit: '',                     //市代收益
        areaProfit: '',                     //区县收益
        firstProfit: '',                    //直推收益
        secProfit: '',                      //间推收益
      }
    }
  },
  computed: {
    dataRule() {
      return {
        imgUrl: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        price: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        marketPrice: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        productId: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        specsOption: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        stock: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        points: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        firstProfit: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        secProfit: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        proProfit: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        cityProfit: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
        areaProfit: [
          {required: true, message: this.$t('validate.required'), trigger: 'blur'}
        ],
      }
    }
  },
  methods: {
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取信息
    getInfo() {
      this.$http.get(`/api/productSpecs/${this.dataForm.id}`).then(({data: res}) => {
        //console.log(res)
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        delete this.dataForm.productDTO
      }).catch(() => {
      })
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/api/productSpecs', this.dataForm).then(({data: res}) => {
          // console.log(res)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {
        })
      })
    }, 1000, {'leading': true, 'trailing': false}),
    // 添加单图添加
    getUrlOne(getUrl){
      this.dataForm.imgUrl = getUrl
    },
    // 添加单图添加
    getUrlTwo(getUrl){
      this.dataForm.bodyImg = getUrl
    },
    // 添加单图添加
    getUrlThree(getUrl){
      this.dataForm.packageImg = getUrl
    },
    // 删除服务器图片
    cancelImg(url,i) {
      this.$http({
        url: `/sys/oss/deleteByUrl`,
        method: 'delete',
        data: {url: url},
      }).then(({data: res}) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        i===1?this.dataForm.imgUrl = '':''
        i===2?this.dataForm.bodyImg = '':''
        i===3?this.dataForm.packageImg = '':''
        if (this.dataForm.id){
          this.$http['put']('/api/productSpecs', this.dataForm).then(({data: res}) => {
          }).catch((err) => {
            this.$message.error(err.msg)
          })
        }
      }).catch(() => {
      })
    },
  }
}
</script>
<style>
.el-upload el-upload-picture-card {
  display: none;
}

.img_con {
  position: relative;
  display: flex;
}

.deduct_img {
  width: 140px;
  height: 140px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.remove_img {
  position: absolute;
  right: 5px;
  top: -5px;
  color: red;
  cursor: pointer;
}
</style>
